package com.bst.common.utils;

import java.util.*;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;

/**
 * Map通用处理方法
 * 
 * @author ruoyi
 */
public class MapDataUtil
{
    public static Map<String, Object> convertDataMap(HttpServletRequest request)
    {
        Map<String, String[]> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<?, ?> entry;
        String name = "";
        String value = "";
        while (entries.hasNext())
        {
            entry = (Entry<?, ?>) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj)
            {
                value = "";
            }
            else if (valueObj instanceof String[])
            {
                String[] values = (String[]) valueObj;
                value = "";
                for (int i = 0; i < values.length; i++)
                {
                    value += values[i] + ",";
                }
                if (value.length() > 0)
                {
                    value = value.substring(0, value.length() - 1);
                }
            }
            else
            {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    //Map根据value进行排序

    /**
     *
     * @param map
     * @param orderType desc,asc
     * @return
     */
    public static Map<String, Integer> valueUpSort(Map<String, Integer> map,String orderType) {

        //map不能为空
        if (map == null || map.isEmpty()) {
            return null;
        }
        //定义一个LinkedHashMap
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();

        List<Map.Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(map.entrySet());
        //比较器
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {

                if("asc".equals(orderType)) { //升序
                    return o2.getValue().compareTo(o1.getValue());
                } else { //降序
                    return o2.getValue().compareTo(o1.getValue());
                }
            }
        });
        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map.Entry<String, Integer> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }
}
